package bizapi.sinosoft.com.provider.order.adapter.impl;

import bizapi.sinosoft.com.provider.order.util.OrderUtil;
import cart.model.jdorder.CSku;
import cart.model.jdorder.Corder;
import cart.model.jdorder.JdOrder;
import cart.model.order.OrderItem;
import cart.model.order.OrderMain;
import cart.model.order.SubOrder;
import cart.model.order.SubOrderItem;
import cart.model.repository.order.OrderRepos;
import cart.model.repository.order.SubOrderRepos;
import com.alibaba.fastjson.JSON;
import com.weibo.api.motan.config.springsupport.annotation.MotanReferer;
import goods.model.ProductFashion;
import goods.model.repository.GoodsRepos;
import goods.model.repository.ProductFashionRepos;
import jd.api.request.order.JdOrderIdEntity;
import jd.api.service.order.JdOrderApi;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import utils.Lang;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by xujingfeng on 2017/1/19.
 */
@Service
public class JdOrderHelper {

    final static Logger logger = LoggerFactory.getLogger(JdOrderHelper.class);

    /**
     * @param orderMainId
     * @param isOccupyStock 是否预占库存
     *                      京东拆单
     *                      A.orderItem关联orderMain 用于主订单展示 拆单时不维护，保持原样
     *                      B.subOrder关联orderMain  用于记录京东拆单
     *                      C.subOrderItem关联subOrder 用于订单详情的拆单展示
     *                      D.subOrderItem关联orderItem subOrderItem用于记录拆单后的商品数量，主要商品信息是还从OrderItem里面取
     */
    @Transactional
    public void splitOrder(String orderMainId, boolean isOccupyStock) {
        long start = System.currentTimeMillis();
        logger.info("start splitOrder...");
        OrderMain orderMain = orderRepos.findById(orderMainId);
        //1.根据订单号查询订单详细信息 jdOrder pOrder cOrder pSku cSku
        Map<String, Object> queryOrder = jdOrderApi.queryOrder(new JdOrderIdEntity(Long.parseLong(orderMain.getThirdOrderNo())));
        JdOrder jdOrder;
        //2.可能返回子订单(不拆单)也可能返回父订单(拆单)
        if (queryOrder.get("type").equals(2)) {
            // type=2 子订单
            queryOrder.put("pOrder", null);
            String jsonString = JSON.toJSONString(queryOrder, true);
            Corder corder = JSON.parseObject(jsonString, Corder.class);
            jdOrder = OrderUtil.createJdOrderByCorder(corder);
            jdOrder = OrderUtil.formatOrder(jdOrder);
        } else {
            // type=1 父订单
            String jsonString = JSON.toJSONString(queryOrder, true);
            jdOrder = JSON.parseObject(jsonString, JdOrder.class);
            jdOrder = OrderUtil.formatOrder(jdOrder);
        }
        //3.判断订单状态(新建订单不需要设置)
        if (!isOccupyStock) {
            orderMain.setStatus(OrderUtil.judgeState(jdOrder));
        }
        //4.生成子订单
        //4.1先删除原子订单关联
        if (!Lang.isEmpty(orderMain.getSubOrders())) {
            subOrderRepos.delete(orderMain.getSubOrders());
            //NOTE ：不清空引用JPA的delete不会起作用
            orderMain.setSubOrders(null);
        }
        //4.2建立新关联
        //4.2.1获取第三方商品和orderItem的映射关系
        List<OrderItem> orderItems = orderMain.getOrderItems();
        Map<String, Object> codeOrderItemRelation = new HashMap<>();
        for (OrderItem orderItem : orderItems) {
            /**Akers 2017/2/7修改： 为便于适配其它商户，第三方产品代码改为统一从productFashion的productCode START */
            ProductFashion productFashion = productFashionRepos.findById(orderItem.getProductFashId());
            codeOrderItemRelation.put(productFashion.getProductCode(), orderItem);
            /**Akers 2017/2/7修改： 为便于适配其它商户，第三方产品代码改为统一从productFashion的productCode END */
        }
        //4.2.2根据京东的corders生成我们的subOrder
        List<SubOrder> subOrders = new ArrayList<>();
        List<Corder> corders = jdOrder.getCorder();
        for (Corder corder : corders) {
            SubOrder subOrder = new SubOrder();
            subOrder.setSubOrderNo(corder.getJdorderid());
            subOrder.setOrder(orderMain);//B
            List<CSku> cskus = corder.getSku();
            List<SubOrderItem> subOrderItems = new ArrayList<>();
            //4.2.3根据cskus生成我们的subOrderItem
            for (CSku cSku : cskus) {
                SubOrderItem subOrderItem = new SubOrderItem();
                subOrderItem.setOrder(orderMain);
                subOrderItem.setCount(cSku.getNum());
                subOrderItem.setOrderItem((OrderItem) codeOrderItemRelation.get(cSku.getSkuid()));//C
                subOrderItem.setSubOrder(subOrder);//D
                subOrderItems.add(subOrderItem);
            }
            subOrder.setSubOrderItems(subOrderItems);
            subOrders.add(subOrder);
        }
        orderMain.setSubOrders(subOrders);
        //4.2.3级联保存
        orderRepos.save(orderMain);
        logger.info("splitOrder end... cost {} ms", System.currentTimeMillis() - start);
    }

    @Autowired
    OrderRepos orderRepos;
    @Autowired
    SubOrderRepos subOrderRepos;
    @Autowired
    GoodsRepos goodsRepos;
    @Autowired
    ProductFashionRepos productFashionRepos;
    @MotanReferer
    JdOrderApi jdOrderApi;
}
